package com.demo.controller.interceptor;

import com.demo.exception.GraceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 继承 HandlerInterceptor 接口, 根据具体需求重写
 * preHandle: 拦截请求，访问controller之前
 * postHandle: 请求访问到controller之后，渲染视图之前
 * afterCompletion: 请求访问到controller之后，渲染视图之后
 * */
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler
    ) throws Exception {
        String userToken = request.getHeader("userToken");

        if (!StringUtils.hasLength(userToken)) {
            log.error("userToken is invalid.");
            GraceException.display("userToken is invalid."); // 抛出自定义异常
            return false; // 请求被拦截
        }

        if (userToken.equalsIgnoreCase("test-demo")) {
            return true; // 请求通过校验, 可以放行, 请求可以继续到达目标 controller 去处理业务
        }

        log.error("not allowed.");
        GraceException.display("not allowed.");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
